package com.bonc.ioc.interceptor;

import com.bonc.ioc.config.OpinionConfig;
import com.bonc.ioc.exceptions.McpException;
import com.bonc.ioc.util.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description 意见插入拦截 IP，1小时只能提交三次意见
 * @Author wxf
 * @Date 2021/4/21
 **/
@Slf4j
@Component
public class OpinionInterceptor implements HandlerInterceptor {
    
    @Autowired
    private OpinionConfig opinionConfig;

    //存放 ip 和 次数
    public static Map<String,Integer> countMap = new HashMap(16);

    //存放 ip 和 时间
    public static Map<String,Long> timeMap = new HashMap(16);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //次数
        Integer limitCount = opinionConfig.getCount();
        //时间
        Long limitTime = opinionConfig.getTime();
        Long nowTime = System.currentTimeMillis() / 1000L;
        String ipAddress = RequestUtil.getIpAddress(request);
        log.info("进入拦截器，拦截意见IP：{}是否满足条件",ipAddress);
        //查看当前ip 数量
        Integer count = countMap.get(ipAddress);
        //查看ip 时间
        Long time = timeMap.get(ipAddress);

        if (time == null && count == null){
            timeMap.put(ipAddress,nowTime);
            countMap.put(ipAddress,1);
        }else {
            if (nowTime - time >= limitTime && count <= limitCount){
                countMap.put(ipAddress,1);
                timeMap.put(ipAddress,nowTime);
            }else if (nowTime - time < limitTime && count < limitCount){
                countMap.put(ipAddress,count+1);
            }else {
                throw new McpException(ipAddress+",此IP在该时间段提交次数上限");
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
